package com.atguigu.oss.service.impl;

/*
 * @ClassName OssServiceImpl
 * @author  忘忧君
 * @Description
 * @Version 1.0
 */

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvatar(MultipartFile file) {

        // Endpoint
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

//        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
//        String objectName = "exampledir/exampleobject.txt";
//        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
//        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
//        String filePath= "D:\\localpath\\examplefile.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = file.getInputStream();

            String fileName = file.getOriginalFilename() ;

            // 1. 文件名称添加uuid 确保文件名唯一
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            // 2. 按照文件日期进行分类
//            new Date();
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(new Date().toString());

            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath +"/"+ fileName;

            // 创建PutObject请求。
            ossClient.putObject(bucketName, fileName, inputStream);

            ossClient.shutdown();

            String url = "https://"+ bucketName +"."+ endpoint +"/"+ fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
